/**
 * 
 */
package top.lcpsky.flashcards.service;

import static com.google.common.collect.Maps.newHashMap;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import top.lcpsky.flashcards.entity.Category;
import top.lcpsky.flashcards.entity.Site;
import top.lcpsky.flashcards.mapper.CategoryMapper;
import top.lcpsky.flashcards.mapper.SiteMapper;
import top.lcpsky.flashcards.util.Pager;


/**   
 * @ClassName:  WebsiteService   
 * @author: lcp
 * @date:   2020年7月7日 下午11:13:35   
 *     
 * @Copyright: 2020 www.ankept.com Inc. All rights reserved. 
 */
@Service
public class WebsiteService {
	@Autowired
	private SiteMapper siteMapper;
	@Autowired
	private CategoryMapper categoryMapper;
	
    public static Pager<Site> pager = null;

	
	public List<Category> getAllWebTypes(){
		return categoryMapper.findAll();
	}
	
	public Map<String,List<Site>> getWebInfoMap(){
		List<Site> webInfos = siteMapper.findAll();
		List<Category> webTypes = this.getAllWebTypes();
		Map<Integer,String> webTypeMap = webTypes.stream().collect(Collectors.toMap(Category::getId, Category::getTitle));
		Map<String, List<Site>> map = newHashMap();
		if(!CollectionUtils.isEmpty(webInfos)) {
			Map<Integer, List<Site>> webInfoMap = webInfos.stream().collect(Collectors.groupingBy(Site::getCategoryId));
			for (Entry<Integer, List<Site>> webTypeEntry : webInfoMap.entrySet()) {
				Integer key = webTypeEntry.getKey();
				List<Site> value = webTypeEntry.getValue();
				String typeName = webTypeMap.get(key);
				map.put(typeName, value);
			}
		}
		return map;
	}
	
	public boolean deleteWebInfo(Integer id) {
		return siteMapper.deleteByPrimaryKey(id)>0;
	}

	/**   
	 * @Title: getPage   
	 * @param: @param map
	 * @param: @param offset
	 * @param: @param limit
	 * @param: @return      
	 * @return: Pager<Site>      
	 * @throws   
	 */
	public Pager<Site> getPage(Map map, int pageNo, int size) {
		  if (map == null) {
	            if (pager != null) {
	                return pager;
	            }
	            map = new HashMap<>();
	        }
	        int total = siteMapper.getTotalCount(map);
	        Pager<Site> page = new Pager<>(total, pageNo, size);
	        map.put("offset", pageNo);
	        map.put("size", size);
	        page.setList(siteMapper.getList(map));
	        if (pager == null) {
	            pager = page;
	        }
	        return page;
	}
}
